package com.kelvin.paopao.module.main.find.list;

import android.Manifest;
import android.text.TextUtils;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.kelvin.kelvinlib.utils.LogUtil;
import com.kelvin.paopao.api.RetrofitService;
import com.kelvin.paopao.api.responseBean.CommonListResponse;
import com.kelvin.paopao.api.responseBean.NearByPersonModel;
import com.kelvin.paopao.utils.Constant;
import com.hyphenate.easeui.utils.SpUtil;
import com.kelvin.paopao.widgets.EmptyLayout;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/5/7.
 */
public class MainFindListPresenter implements IMainFindListPresenter {

    private MainFindListFragment mView;

    private int page_index = 1;

    private String user_sex, user_tizhong, user_shengao, user_label;

    private LocationClient locationClient;
    private MyBDLocationListener bdLocationListener;

    private String type;

    public MainFindListPresenter(MainFindListFragment mView) {
        this.mView = mView;

        locationClient = new LocationClient(mView.getActivity().getApplicationContext());
        bdLocationListener = new MyBDLocationListener();
        // 注册监听
        locationClient.registerLocationListener(bdLocationListener);
    }

    private boolean mRefresh;

    public void requestLocation(boolean isRefresh) {
        this.mRefresh = isRefresh;
        if (Constant.longtitude == 0 || Constant.latitude == 0) {
            getPermission();
        } else {
            if (!TextUtils.isEmpty(SpUtil.getLoginphone(mView.getContext()))) {
                updateLocation(Constant.longtitude, Constant.latitude);
            }
            getNearPerson(isRefresh);
        }
    }


    public void updateLocation(double latitude, double longtitude) {
        RetrofitService.updateLocation(String.valueOf(longtitude), String.valueOf(latitude)).
                doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        mView.showLoading();
                    }
                }).subscribeOn(AndroidSchedulers.mainThread()) // 指定主线程
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<CommonListResponse>() {
            @Override
            public void accept(@NonNull CommonListResponse commonListResponse) throws Exception {

            }
        });
    }


    @Override
    public void getData(boolean isRefresh) {
//        requestLocation(isRefresh);
    }

    private void getNearPerson(final boolean isRefresh) {
        page_index = 1;
        RetrofitService.getNearPerson(String.valueOf(Constant.longtitude),
                String.valueOf(Constant.longtitude),
                String.valueOf(page_index), user_sex, user_shengao, user_tizhong, user_label, type).
                compose(mView.<CommonListResponse<NearByPersonModel>>bindToLife()).subscribe(new Consumer<CommonListResponse<NearByPersonModel>>() {
            @Override
            public void accept(@NonNull CommonListResponse<NearByPersonModel> response) throws Exception {

                mView.hideLoading();
                if (isRefresh) {
                    mView.finishRefresh();
                }
                if (response.getResult() != null && response.getResult().size() != 0) {
                    //更新数据
                    mView.loadData(response);
                } else {
                    mView.showNoData();
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {

            }
        }, new Action() {
            @Override
            public void run() throws Exception {

            }
        });
    }


    @Override
    public void getMoreData() {
        page_index++;
        RetrofitService.getNearPerson(String.valueOf(Constant.longtitude),
                String.valueOf(Constant.latitude),
                String.valueOf(page_index), user_sex, user_shengao, user_tizhong, user_label, type).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(@NonNull Disposable disposable) throws Exception {

            }
        }).compose(mView.<CommonListResponse<NearByPersonModel>>bindToLife()).
                subscribe(new Consumer<CommonListResponse<NearByPersonModel>>() {
                    @Override
                    public void accept(@NonNull CommonListResponse<NearByPersonModel> response) throws Exception {
                        mView.loadMoreData(response);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {

                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {

                    }
                });
    }

    @Override
    public void getDataWithFilter(String user_sex, String user_tizhong, String user_shengao, String user_label) {
        page_index = 1;
        this.user_sex = user_sex;
        this.user_tizhong = user_tizhong;
        this.user_shengao = user_shengao;
        this.user_label = user_label;

        RetrofitService.getNearPerson(String.valueOf(Constant.longtitude),
                String.valueOf(Constant.longtitude),
                String.valueOf(page_index), user_sex, user_shengao, user_tizhong, user_label, type).
                doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        mView.startRefresh();
                    }
                }).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).
                compose(mView.<CommonListResponse<NearByPersonModel>>bindToLife()).subscribe(new Consumer<CommonListResponse<NearByPersonModel>>() {
            @Override
            public void accept(@NonNull CommonListResponse<NearByPersonModel> response) throws Exception {
                //更新数据
                mView.finishRefresh();

                if (response.getResult() != null && response.getResult().size() != 0) {
                    //更新数据
                    mView.loadData(response);
                } else {
                    mView.showNoData();
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {

            }
        }, new Action() {
            @Override
            public void run() throws Exception {

            }
        });
    }

    @Override
    public void getData(boolean isRefresh, String type) {
        this.type = type;
        requestLocation(isRefresh);
    }


    /**
     * 获取权限
     */
    private void getPermission() {
        RxPermissions rxPermission = new RxPermissions(mView.getActivity());
        rxPermission
                .requestEach(Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            //全部同意
                            getLocation();
                        } else {
                            //顯示錯誤
                            mView.showNetError(new EmptyLayout.OnRetryListener() {
                                @Override
                                public void onRetry() {
                                    getPermission();
                                }
                            });
                        }
                    }
                });
    }

    /**
     * 获得所在位置经纬度及详细地址
     */
    public void getLocation() {
        // 声明定位参数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式 高精度
        option.setOpenGps(true);
        option.setCoorType("bd09ll");// 设置返回定位结果是百度经纬度 默认gcj02
        option.setScanSpan(10000);// 设置发起定位请求的时间间隔 单位ms
        option.setIsNeedAddress(true);// 设置定位结果包含地址信息
        // 设置定位参数
        locationClient.setLocOption(option);
        // 启动定位
        locationClient.start();

    }

    private class MyBDLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // 非空判断
            if (location != null) {
                // 根据BDLocation 对象获得经纬度以及详细地址信息
                LogUtil.d("loc type:" + location.getLocType());

                double latitude = location.getLatitude();
                double longtitude = location.getLongitude();
                String city = location.getCity();
                String province = location.getProvince();

                Constant.city = city;
                Constant.provice = province;
                Constant.latitude = latitude;
                Constant.longtitude = longtitude;

                LogUtil.d(" latitude:" + latitude + ",longtitude" + longtitude);

                if (latitude != 0 && longtitude != 0) {

                    SpUtil.putLatitude(mView.getContext(), String.valueOf(latitude));
                    SpUtil.putLongtitude(mView.getContext(), String.valueOf(longtitude));

                    if (!TextUtils.isEmpty(SpUtil.getLoginHuanxin_id(mView.getContext()))) {
                        updateLocation(longtitude, latitude);
                    }
                    getNearPerson(mRefresh);

                    if (locationClient.isStarted()) {
                        // 获得位置之后停止定位
                        locationClient.stop();
                    }
                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }
}
